package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.common.StatusCode;
import com.example.demo.model.Dishes;
import com.example.demo.model.Ingredients;
import com.example.demo.service.IngredientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/ingredients")
public class IngredientsController {
    @Autowired
    private IngredientService ingredientService;

    @PostMapping("/generate-image")
    public ResponseEntity<Result<byte[]>> generateImage(@RequestBody List<String> selectedIngredients) throws SQLException {
        byte[] imageData = ingredientService.generateImageFromIngredients(selectedIngredients);
        return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(new Result<>(true, StatusCode.OK, "生成图片成功", imageData));
    }

    @PostMapping("/generate-dish")
    public ResponseEntity<Result<Dishes>> generateDishWithImage(@RequestParam String dishName,
                                                                @RequestBody List<String> selectedIngredients) throws SQLException {
        byte[] imageData = ingredientService.generateImageFromIngredients(selectedIngredients);
        String base64Image = Base64.getEncoder().encodeToString(imageData);

        // 根据食材名称查找对应的食材，并转换为食材对象列表
        List<Ingredients> ingredientList = new ArrayList<>();
        for (String ingredientName : selectedIngredients) {
            Ingredients ingredient = ingredientService.getIngredientByName(ingredientName);
            ingredientList.add(ingredient);
        }
        // 创建菜品对象并设置属性
        Dishes dish = new Dishes(dishName, ingredientList, base64Image);

        return ResponseEntity.ok().body(new Result<>(true, StatusCode.OK, "生成菜品成功", dish));
    }

}
